<?php

namespace App\Http\Controllers\Home;

use DB;
use Illuminate\Http\Request;
use EasyWeChat\Foundation\Application;
use App\Http\Controllers\Controller;
use App\Http\Controllers\QueryController;

use App\Http\Models\Post;
use App\Http\Models\Menu;
use App\Http\Models\Top;

class IndexController extends Controller {

    protected $query = null;

    public function __construct(){
        $this->query = new QueryController();
    }

    public function index()
    {

        $posts = Post::orderBy('created_at','desc');
        $posts = $posts -> paginate(20);


        return view('home.index',['posts'=>$posts,'query'=>$this->query]);
    }

    //第一个 模块根据传入的参数自带相关模块数据查询功能
    //第二个 提供统一的模板查询函数
    public function posts(Request $request)
    {
        $cid = $request -> input('cid');
        $posts = Post::where('cid',$cid)->paginate(10);
        //分页处理
        $requestUri = preg_replace('/&page=\d+/',"",$request->getRequestUri());
        $posts->setPath($requestUri);

        return view('home.posts',['posts'=>$posts,'query'=>$this->query,'cid'=>$cid]);
    }

    public function post($id)
    {
        $post = Post::find($id);

        //记录点击
        $post->pv = $post->pv+1;
        $post->save();

        //排行数据
        $time = time();
        $month = date('m',$time);//一年中的第几月
        $week = date('W',$time);//一年中的第几周
        $year = date('Y',$time);

        $where = ['post_id'=>$id,'month'=>$month,'week'=>$week,'year'=>$year];
        $top = Top::where($where)->get();
        if(!count($top)){
            $top = new Top;
            $top->title = $post->title;
            $top->post_id = $id;
            $top->pv = 1;
            $top->year  = $year;
            $top->month = $month;
            $top->week  = $week;
            $top->save();
        }else{
            Top::where($where)->update(['pv'=>$top[0]['pv']+1]);
        }



        return view('home.post',['post'=>$post,'query'=>$this->query]);
    }



    public function search($keyword){

        $posts = Post::where('title','like',"%{$keyword}%")->paginate(20);
        foreach($posts as $key => $val ){
            //$posts[$key][$val]['title'] = str_replace("{$keyword}","<b color='red'>{$keyword}</b>",$val['title']);
            $val->title = str_replace("{$keyword}","<b style='color:red;'>{$keyword}</b>",$val->title);
            $val->description = str_replace("{$keyword}","<b style='color:red;'>{$keyword}</b>",mb_substr($val->description,0,200));
        }

        return view('home.search',['posts'=>$posts,'query'=>$this->query,'keyword'=>$keyword]);
    }


    public function edit()
    {
        return view('home.edit');
    }

    public function content()
    {
        return view('home.content');
    }

}
